﻿using System;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using EnvDTE;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Security.Cryptography;
using System.Collections;
using System.Diagnostics;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.Common;
using Microsoft.Practices.ComponentModel;

namespace SteriaMummert.SharePoint.SoftwareFactoryLite.ValueProviders
{
    [ServiceDependency(typeof(DTE))]
    public class ApplicationConfigValueProvider : ValueProvider, IAttributesConfigurable
    {
        private string _ConfigValue = "";
        public string ConfigValue
        {
            get { return _ConfigValue; }
            set { _ConfigValue = value; }
        }

        private XmlDocument GetApplicationConfigFile(DTE dte)
        {
            //Path to the solution directory
            string solutionDirectory = Path.GetDirectoryName((string)dte.Solution.Properties.Item("Path").Value);
            string toPath = Path.Combine(solutionDirectory, "ApplicationConfiguration.xml");

            XmlDocument doc = new XmlDocument();

            if (File.Exists(toPath))
            {
                doc.Load(toPath);
            }
            return doc;
        }

        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            newValue = "";

            DTE service = (DTE)this.GetService(typeof(DTE));
            XmlDocument doc = GetApplicationConfigFile(service);

            XmlNode node = doc.SelectSingleNode("/ApplicationConfiguration/" + ConfigValue);
            if (node != null)
            {
                newValue = node.InnerText;
            }

            return true;
        }

        #region IAttributesConfigurable Members

        void IAttributesConfigurable.Configure(System.Collections.Specialized.StringDictionary attributes)
        {
            if(attributes["ConfigValue"] != null)
            {
                ConfigValue = attributes["ConfigValue"];
            }
        }

        #endregion
    }
}

